import time
import pyautogui
import pyperclip
import pygetwindow as gw

# 读取账号密码文件
def read_accounts(file_path='./files/accounts.txt'):
    accounts = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            if '----' in line:
                user, pwd = line.strip().split('----', 1)
                accounts.append((user, pwd))
    return accounts

# 查找所有 Steam 登录窗口
def find_steam_windows():
    # 根据标题模糊匹配 Steam 登录窗口
    steam_windows = gw.getWindowsWithTitle("Steam")
    login_windows = [w for w in steam_windows if "登录" in w.title or "Sign in" in w.title]
    return login_windows

# 自动登录函数
def auto_login_steam(username, password):
    pyperclip.copy(username)

    print(f"正在登录: {username}")
    
    # 激活窗口
    window = gw.getActiveWindow()
    window.activate()
    time.sleep(0.5)  # 等待窗口聚焦

    # 清除已有内容（可选）
    pyautogui.hotkey('ctrl', 'a')
    pyautogui.press('delete')

    # 输入用户名
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.press('tab')  # 切换到密码框

    # 输入密码
    pyperclip.copy(password)
    pyautogui.hotkey('ctrl', 'v')

    # 回车登录
    time.sleep(0.3)
    pyautogui.press('enter')

# 主程序入口
if __name__ == '__main__':
    accounts = read_accounts()
    windows = find_steam_windows()

    if not windows:
        print("未找到任何 Steam 登录窗口。")
        exit()

    print(f"共找到 {len(windows)} 个 Steam 登录窗口。")

    for idx, window in enumerate(windows):
        username, password = accounts[idx % len(accounts)]  # 循环使用账号
        window.activate()
        auto_login_steam(username, password)
        time.sleep(2)  # 每次登录间隔时间（根据网络情况调整）